var BaseConsultDo = app.controller('BaseConsultDo', function($rootScope, $scope, $http,$state,$stateParams,$cordovaDevice,$interval,$cordovaFileTransfer,BaseConsultDoTitle,BaseConsultDoData) {
	try{
		$rootScope.showf=false;
		$scope.show=false;
		$scope.showm=false;
		$scope.vshow=true;
		$scope.dshow=false;
		$rootScope.title = BaseConsultDoTitle.cate_name;
		$scope.fcate=[];
		$scope.tutor=[];
		$scope.cate_id=0;
		$scope.content='';
		$scope.voice_path='';
		$scope.voice_size=0;
		$scope.tel='';
		$scope.msg='';

		$scope.temppath='';
		$scope.playm="tutor_video.png";

		$scope.keyPress=function(e){
			if(e.which==13){
				$scope.fordone();
			}
		}
		
		//获取咨询类型
		var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=fcategory&id="+$stateParams.id;
		$http.jsonp(url).success(function(data) {
			$scope.fcate=data.retval;
			if($stateParams.cid!=undefined&&$stateParams.cid>0){
				for ( var i = 0; i < $scope.fcate.length; i++) {
					if($scope.fcate[i].cate_id==$stateParams.cid){
						$scope.fcate[i].h=1;
						$scope.cate_id=$scope.fcate[i].cate_id;
					}
				}
			}
		});

		//获取专家列表
		var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=tutors&id="+$stateParams.id;
		$http.jsonp(url).success(function(data) {
			$scope.tutor=data.retval;
		});

		//获取用户信息
		$scope.user={};
		var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=userinfo";
		$http.jsonp(url).success(function(data) {
			$scope.user=data.retval;
			
			if($scope.user!=undefined&&$scope.user!=null&&$scope.user!=""&&$scope.user.phone_tel!=undefined&&$scope.user.phone_tel!=null&&$scope.user.phone_tel!=""){
				$scope.tel=$scope.user.phone_tel;
			}
			
		});
		
		$scope.timer=null;
		$scope.v_start=false;
		$scope.ms=0;
		$scope.ss=0;
		$scope.v_move = 0;
		$scope.audiostart=function(){
			try{

				$scope.voice_size = 0;
				$scope.ms=0;
				$scope.ss=0;
				$scope.voice_path="";
				$scope.temppath='';
				$scope.v_start=true;
				$scope.v_move = 0;
				if($scope.timer!=null)
					$interval.cancel($scope.timer);
				$scope.timer =  $interval(function(){			
					if($scope.v_start){
						$scope.voice_size++;
						$scope.ms=parseInt($scope.voice_size/60);
						$scope.ss=parseInt($scope.voice_size%60);
					}else{
						$interval.cancel($scope.timer);
					}
				},1000);
				console.log('start');
				window.plugins.audioRecorderAPI.record(function(msg) {
					// complete
					console.log('record ok: ' + msg);
				}, function(msg) {
					// failed
					console.log('record err'+msg);
				}, 600); // record 30 seconds
			}catch(e){showcatch(e);$scope.audioclear();}
		};

		$scope.audioclear=function(){
			try{
				$scope.v_start=false;
				$scope.voice_path="";
				$scope.temppath='';
				$scope.voice_size=0;
				$scope.v_move = 0;
				$scope.ms=0;
				$scope.ss=0;
				if($scope.timer!=null)
					$interval.cancel($scope.timer);
				console.log('clear');
				if ($rootScope.media != undefined && $rootScope.media != null) {
					$rootScope.media.release();
				}
				window.plugins.audioRecorderAPI.stop(function(audiopath) {
					// success
					
				}, function(msg) {
					// failed
					//alert('ko: ' + msg);
					console.log('stop err'+msg);
				});
				
			}catch(e){showcatch(e);}
		};
		$scope.audiostop=function(){
			try{
				$scope.v_start=false;
				$scope.v_move = 0;
				if($scope.timer!=null){
					$interval.cancel($scope.timer);
				}
				console.log('end');
				window.plugins.audioRecorderAPI.stop(function(audiopath) {
					// success
					console.log('ok: ' + audiopath);
					/*if($rootScope.isf){
						$rootScope.isf=false;
						return false;
					}*/
					if($scope.voice_size<=3){
						showtoast('录音时间太短');
						return false;
					}
					$scope.upfile(audiopath);
					$scope.$apply();
				}, function(msg) {
					// failed
					//alert('ko: ' + msg);
					console.log('stop err'+msg);
				});
			}catch(e){showcatch(e);$scope.audioclear();}
		};
		
		
		/*if($rootScope.isf){
			$scope.audiostart();
			setTimeout(function () {
				$scope.audiostop();
			}, 1100);
		}*/

		//选择擅长领域
		$scope.choosecate=function(t){
			var n=t.f;
			if(n.h>0){
				$scope.fcate[t.$index].h=0;
				$scope.cate_id=0;
			}else{
				var h=0;
				for(var i=0;i<$scope.fcate.length;i++){
					$scope.fcate[i].h=0;
				}

				$scope.fcate[t.$index].h=1;
				$scope.cate_id=$scope.fcate[t.$index].cate_id;
			}

			var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=tutors&id="+n.cate_id;
			$http.jsonp(url).success(function(data) {
				$scope.tutor=data.retval;
			});
		}

		//弹出手机验证
		$scope.fordone=function(){
			var cate_id=$scope.cate_id;
			var content=$scope.content;
			var voice_path=$scope.voice_path;
			var voice_size=$scope.voice_size;
			if(cate_id<=0){
				showtoast("请选择咨询领域");
				return false;
			}
			if(voice_path==""||voice_path==undefined||voice_path==null||voice_size<=0){
				if(content==''||content==null||content==undefined){
					showtoast("请填写咨询内容");
					return false;
				}

				if(content.length<=30||content.length>=500){
					showtoast("请填写30到500个字");
					return false;
				}
			}

			if($scope.user==undefined||$scope.user==null||$scope.user==""||$scope.user.phone_tel==undefined||$scope.user.phone_tel==null||$scope.user.phone_tel==""){
				$scope.show=true;
			}
			else{
				$scope.done();
			}
		}

		$scope.validate_code='';
		//完成订单
		$scope.busydone=false;
		$scope.done=function(){
			if($scope.busydone){
				return false;
			}

			var cate_id=$scope.cate_id;
			var content=$scope.content;
			var voice_path=$scope.voice_path;
			var voice_size=$scope.voice_size;
			var tel=$scope.tel;
			var code=$scope.validate_code;

			try{
				var model = $cordovaDevice.getModel();
				var platform = $cordovaDevice.getPlatform();
				var uuid = $cordovaDevice.getUUID();
			}
			catch(ex){
				var model = 'web';
				var platform = 'web1';
				var uuid = '12312312312';
			}

			if($scope.show){
				if(tel==''||tel==null||tel==undefined){
					showtoast("请先验证手机");
					return false;
				}

				if(code==''||code==null||code==undefined){
					showtoast("请输入验证码");
					return false;
				}
			}

			if(cate_id<=0){
				showtoast("请选择咨询领域");
				return false;
			}

			if(voice_path==""||voice_path==undefined||voice_path==null||voice_size<=0){
				if(content.length<=30||content.length>=500){
					showtoast("请填写30到500个字");
					return false;
				}

				if(content==''||content==null||content==undefined){
					showtoast("请填写咨询内容");
					return false;
				}
			}
			$scope.busydone=true;

			var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=consultdone" 
			+"&cate_id="+cate_id
			+"&content="+content
			+"&voice_path="+voice_path
			+"&voice_size="+voice_size
			+"&tel="+tel
			+"&code="+code
			+"&model="+model
			+"&platform="+platform
			+"&uuid="+uuid+"&tid="+$stateParams.tid;

			$http.jsonp(url).success(function(data) {
				if(data.done){
					//showtoast(data.msg);
					//showdialog("发布咨询成功，点击确定跳转到咨询列表页面");
					$scope.msg=data.msg;
					$scope.show=false;
					$scope.showm=false;
					$scope.dshow=true;
				}else{
					$scope.busydone=false;
				}
			});
		}

		$scope.busy=false;
		$rootScope.code_value = '发送验证码';
		$scope.get_code=function(){
			if($scope.busy){
				return false;
			}
			var reg = /(^13\d{9}$)|(^14)[5,7]\d{8}$|(^15[0,1,2,3,5,6,7,8,9]\d{8}$)|(^17)[6,7,8]\d{8}$|(^18\d{9}$)/g ;  
			if(!reg.test($scope.tel)){  
				showtoast("请输入正确的手机");
				return false;
			} 

			$scope.busy=true;
			var url=SITE_URL+"index.php?app=userapp&act=authcode&t="+$scope.tel+"&callback=JSON_CALLBACK&type=consult";
			$http.jsonp(url).success(function(data) {
				if(data.done){

					$scope.code_num = 60;
					$rootScope.code_value = '秒后重发';
					var myTime = setInterval(function() {
						$scope.code_num--;
						$scope.$apply(); // 通知视图模型的变化

						if($scope.code_num==0){

							$scope.busy=false;
							$rootScope.code_value = '获取验证码';
							$scope.code_num =  '';
							clearInterval(myTime);
							$scope.$apply();
						}
					}, 1000);	
				}else{
					$scope.busy=false;
				}
			}).error(function(){$scope.busy=false;});
		}

		$scope.itemOnLongPress = function() {
			$scope.audiostart();
		}

		$scope.itemOnTouchEnd = function() {
			$scope.audiostop();
		}

		$scope.itemOnTouchMove = function() {
			$scope.audioclear();
		}


	

		$scope.upfile=function(audiopath){
			// 上传
			msglengthapp=0;
			url=$rootScope.site+"index.php?app=usermyapp&act=upfile&callback=JSON_CALLBACK";
			$http.jsonp(url).success( function(data) {
				console.log(data);
				if(data.done){
					$rootScope.ECM_ID=data.retval.userid;
					$rootScope.HTTP_USER_AGENT = data.retval.HTTP_USER_AGENT;
					var uri = $rootScope.site+'index.php?app=appuploadvideo&ajax=ajax&XDEBUG_SESSION_START=ECLIPSE_DBGP';
					console.log(uri);
					var options = new FileUploadOptions();
					options.fileKey="file";
					options.fileName=audiopath.substr(audiopath.lastIndexOf('/')+1);
					options.mimeType="text/plain";
					var params = {};
					params.ECM_ID = $rootScope.ECM_ID;
					params.HTTP_USER_AGENT = $rootScope.HTTP_USER_AGENT;
					params.belong = 10;
					params.item_id = JSON.parse(window.localStorage.user).CHATUSER;;
					options.params = params;
					ProgressIndicator.showProgressBar('正在发送...');
					$cordovaFileTransfer.upload(uri,audiopath,options).then(function (r) {
						console.log("Code = " + r.responseCode);
						console.log("Response = " + r.response);
						console.log("Sent = " + r.bytesSent);
						ProgressIndicator.hide();
						//alert(r.response);
						data = JSON.parse(r.response);
						if(data.done){
							$scope.voice_path=data.retval.file_path;
						}
						else{
							showtoast(data.msg);
						}
					}, function (error) {
						console.log("An error has occurred: Code = " + error.code);
						console.log("upload error source " + error.source);
						console.log("upload error target " + error.target);
						console.log("upload error target ", error);
						ProgressIndicator.hide();
						showtoast('发送失败，'+error);
					}, function(progressEvent) {
						ProgressIndicator.setProgress(progressEvent.loaded / progressEvent.total);
					});
				}
			});
		}

		$scope.isplay=false;
		$scope.play = function(){
			try{
				if($scope.voice_path!=null&&$scope.voice_path!=''){
					//播放音频 m 即为音频地址
					if(!$scope.isplay){
						
						if($rootScope.media!=undefined&&$rootScope.media!=null){
							$rootScope.media.release();
						}
						
						$rootScope.media=audioplay($rootScope.site+$scope.voice_path);
						console.log('newplay');
						console.log($rootScope.media.src);
						$rootScope.media.successCallback=function(){
							$scope.playm="tutor_video.png";
							$scope.isplay=false;
							console.log('successCallback png');
							console.log($scope.playm);
							$scope.$apply();
						};
						$rootScope.media.errorCallback=function(err){
							$scope.playm="tutor_video.png";
							$scope.isplay=false;
							console.log('successCallback png');
							console.log($scope.playm);
							$scope.$apply();
						};

						$scope.playm="write_d.gif";
						console.log('newplay png');
						console.log($scope.playm);
						$rootScope.media.play();
						$scope.isplay=true;
					}
				}
			}
			catch(e){
				console.log('play');
				console.log(e);
			}
		}
	}
	catch (e) {
		showcatch(e);
	}
});

//获取上级类别
BaseConsultDo.BaseConsultDoTitle=function($q,$stateParams,$http){
	var def = $q.defer();
	var url=SITE_URL+"index.php?app=baseloginapp&callback=JSON_CALLBACK&act=fcateinfo&id="+$stateParams.id;
	$http.jsonp(url).success(function(data) {
		def.resolve(data.retval);
	});
	return def.promise;
}
BaseConsultDo.BaseConsultDoData=function($q, $http,$stateParams,$rootScope){
	try {
		var data = [];
		var def = $q.defer();
		if(window.localStorage.u==undefined||window.localStorage.u==null||window.localStorage.u==""){			
			$rootScope.go("loginmain");
		}else{
			def.resolve(data);
		}

		return def.promise;
	} catch (e) {
		showcatch(e);
	}
}
